package com.smart.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.smart.common.enums.ConstructionStatusEnum;
import com.smart.helper.CommonUtil;
import com.smart.mapper.ProjectOldMapper;
import com.smart.model.domain.*;
import com.smart.service.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.tuple.Pair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @author zhanghong
 */
@Slf4j
@Service
public class ProjectOldServiceImpl extends ServiceImpl<ProjectOldMapper, ProjectOldDO> implements ProjectOldService {
    @Autowired
    private ProjectService projectService;
    @Autowired
    private PortService portService;
    @Autowired
    private AccessService accessService;
    @Autowired
    private QrCodeService qrCodeService;
    @Autowired
    private ManageTempUserRegistrationService manageTempUserRegistrationService;

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public void projectTransfer() {
//        List<ProjectOldDO> buildList = lambdaQuery().eq(ProjectOldDO::getId, 7).list();
        //查询老数据
        List<ProjectOldDO> buildList = lambdaQuery().ne(ProjectOldDO::getState, -1).list();
        for (Pair<Long, ProjectDO> item : buildList(buildList)) {
            Long oldProjectId = item.getLeft();
            //写入项目信息
            ProjectDO projectDO = item.getRight();
            projectService.save(projectDO);
            //写入进出口信息
            portInfo(oldProjectId, projectDO);
        }

//        //写入新数据
//        projectService.saveBatch();
    }

    private void portInfo(Long oldId, ProjectDO projectDO) {
        // 查询老的进出口信息
        List<PortDO> list = portService.lambdaQuery().eq(PortDO::getProjectId, oldId).list();
        if (CollectionUtils.isEmpty(list)) {
            return;
        }
        // 写入新的进出口信息
        // key-老的进出口id， value-新的进出口id
        Map<Long, Long> portIdMapping = new HashMap<>();
        for (PortDO portDO : list) {
            Boolean addressType = null;
            if (portDO.getType() == 1) {
                addressType = Boolean.TRUE;
            } else if (portDO.getType() == 2) {
                addressType = Boolean.FALSE;
            }
            Long accessId = qrCodeService.qrCode(null, null, true, projectDO.getId(), portDO.getName(), addressType);
            portIdMapping.put(portDO.getId(), accessId);
        }

        //写入进出口记录
        List<AccessDO> accessList = accessService.lambdaQuery().eq(AccessDO::getProjectId, oldId).list();
        List<ManageTempUserRegistrationDO> registrationList = build(projectDO, portIdMapping, accessList);
        for (ManageTempUserRegistrationDO registrationDO : registrationList) {
            try {
                manageTempUserRegistrationService.save(registrationDO);
            } catch (Exception e) {
                log.error("失败数据 {}", JSON.toJSONString(registrationDO));
                e.printStackTrace();
//                throw e;
            }
        }
    }

    private List<ManageTempUserRegistrationDO> build(ProjectDO projectDO, Map<Long, Long> portIdMapping, List<AccessDO> accessList) {
        List<ManageTempUserRegistrationDO> registrationDOS = Lists.newArrayList();
        for (AccessDO accessDO : accessList) {
            ManageTempUserRegistrationDO registrationDO = new ManageTempUserRegistrationDO();
            registrationDO.setProjectId(projectDO.getId());
            registrationDO.setUserName(accessDO.getName());
            registrationDO.setUserPhone(accessDO.getPhone());
            registrationDO.setIdNumber(accessDO.getIdNumber());
            registrationDO.setAddress(accessDO.getAddr());
            registrationDO.setAddressDetails(accessDO.getAddr());
            registrationDO.setReceiver(accessDO.getReception());
            registrationDO.setLeaveOrNot(0);//默认离场
            if (accessDO.getInTime() !=null) {
                registrationDO.setLeaveOrNot(1);//在场
                registrationDO.setEntranceAddress(portIdMapping.get(accessDO.getInPortId()));//进场出口
            }
            if (accessDO.getOutTime() !=null) {
                registrationDO.setLeaveOrNot(0);//离场
                registrationDO.setApproachAddress(portIdMapping.get(accessDO.getOutPortId()));//离场出口
            }
            registrationDO.setApproachTime(accessDO.getOutTime());

            registrationDO.setEntranceTime(accessDO.getInTime());
            registrationDO.setProvince(CommonUtil.provinceMap.get(accessDO.getProvinceCode()));//省
            registrationDO.setCity(CommonUtil.cityMap.get(accessDO.getCityCode()));//市
            registrationDO.setArea(CommonUtil.areaMap.get(accessDO.getAreaCode()));//区

            registrationDOS.add(registrationDO);
        }
        return registrationDOS;
    }

    private List<Pair<Long, ProjectDO>> buildList(List<ProjectOldDO> oldList) {
        return oldList.stream().map(this::build).collect(Collectors.toList());
    }

    private Pair<Long, ProjectDO> build(ProjectOldDO old) {
        ProjectDO projectDO = new ProjectDO();
        projectDO.setProjectName(old.getName());
        if (!Objects.equals(old.getNumber(), "无编号")) {
            projectDO.setProjectNumber(old.getNumber());
        }
        projectDO.setEngineeringType(engineeringTypeConvert(old.getGongchengTypeId()));
        projectDO.setEngineeringCost(old.getCost());
        projectDO.setConstructionStatus(constructionStatusConvert(old.getShigongStateId()));
        projectDO.setQualityRegistrationNumber(old.getQualityNumber());
        projectDO.setLocation(old.getLocation());
        projectDO.setStartDate(old.getStartDate());
        projectDO.setFloorArea(old.getFloorage());
        projectDO.setStreetCode(old.getStreetCode());
        projectDO.setAddress(old.getAddr());
        projectDO.setShigongUnit(old.getShigongUnit());
        projectDO.setShigongHeadName(old.getShigongHeadName());
        projectDO.setShigongHeadJob(old.getShigongHeadJob());
        projectDO.setShigongHeadPhone(old.getShigongHeadPhone());
        projectDO.setShigongContactJob(old.getShigongContactJob());
        projectDO.setShigongContactName(old.getShigongContactName());
        projectDO.setShigongContactPhone(old.getShigongContactPhone());
        projectDO.setJiansheUnit(old.getJiansheUnit());
        projectDO.setJiansheHeadName(old.getJiansheHeadName());
        projectDO.setJiansheHeadPhone(old.getJiansheHeadPhone());
        projectDO.setJianliUnit(old.getJiansheUnit());
        projectDO.setJianliHeadName(old.getJianliHeadName());
        projectDO.setJianliHeadPhone(old.getJianliHeadPhone());
        projectDO.setAccount(old.getUserName());
        projectDO.setPassword(old.getPassword());
        fill(projectDO, old.getState());
        projectDO.setCreateTime(old.getAddTime());
        return Pair.of(old.getId(), projectDO);
    }

    private void fill(ProjectDO projectDO, Long state) {
        if (state == 1) {
            projectDO.setAuditType("NEW");
            projectDO.setAuditStatus("WAIT");
            projectDO.setValid(0);
        }
        if (state == -1) {
            projectDO.setAuditType("NORMAL");
            projectDO.setAuditStatus("REJECT");
            projectDO.setValid(0);
        }
        if (state == 2 || state == 5) {
            projectDO.setAuditType("NORMAL");
            projectDO.setAuditStatus("PASS");
            projectDO.setValid(1);
        }
    }


    private String engineeringTypeConvert(Long typeId) {
        if (typeId == 1) {
            return "COMMERCIAL_HOUSING";
        }
        if (typeId == 2) {
            return "AFFORDABLE_HOUSING";
        }
        if (typeId == 3) {
            return "PUBLIC_BUILDINGS";
        }
        if (typeId == 4) {
            return "INDUSTRIAL_BUILDINGS";
        }
        if (typeId == 5) {
            return "MUNICIPAL";
        }
        if (typeId == 6) {
            return "DECORATION";
        }
        if (typeId == 7) {
            return "HOUSE_ALTERATION";
        }

        return null;
    }

    private String constructionStatusConvert(Long stateId) {
        if (stateId == 1) {
            return ConstructionStatusEnum.UN_START.name();
        }
        if (stateId == 2) {
            return ConstructionStatusEnum.RUNNING.name();
        }if (stateId == 3) {
            return ConstructionStatusEnum.STOP.name();
        }if (stateId == 4) {
            return ConstructionStatusEnum.WAIT_ACCEPT.name();
        }if (stateId == 5) {
            return ConstructionStatusEnum.FINISH.name();
        }if (stateId == 6) {
            return ConstructionStatusEnum.DIE.name();
        }
        return null;
    }
}
